<?php
if (file_exists(APPPATH.'models/basemodel.php')) include_once(APPPATH.'models/basemodel.php');

class ContactModel extends BaseModel {

	public function ContactModel() {
		parent::BaseModel();
		$this->setModel('contact');
		$this->obj =& get_instance();
		$this->load->database();
	}
	
	public function getContactsForCompany($companyid) {
		$sql = "SELECT C.*
				FROM contact C INNER JOIN company_contact CC ON (C.id = CC.contactid)
				WHERE CC.companyid = ".intval($companyid)." 
				ORDER BY C.surname";
		
		$rs = $this->db->query($sql)->result();
		
		if (count($rs)) return $rs;
		else return false;
	}
	
	public function retrieve_by_pkey($idField) {
		$sql = "SELECT T.*, F.friendly_url, CONCAT_WS(' ', U.firstname, U.lastname) as creator, CONCAT_WS(' ', U2.firstname, U2.lastname) as updater, U3.id as usersid
				FROM ".$this->db_table." T LEFT JOIN friendly_urls F ON (T.id = F.contentid AND F.content_type = ".$this->db->escape($this->db_table).")
						LEFT JOIN users U3 ON (T.email1 = U3.emailaddress AND U3.deleted = 0 )
						LEFT JOIN users U ON (T.creatorid = U.id)
						LEFT JOIN users U2 ON (T.updaterid = U2.id)
				WHERE T.id = ".intval($idField)."
				LIMIT 1";

		$rs = $this->db->query($sql)->result();

		if (count($rs)) return $rs[0];
		else return false;
	}
	
	public function getCurrentCompany($contactid) {
		$sql = "SELECT C.*
				FROM company C INNER JOIN company_contact CC ON (C.id = CC.companyid)
				WHERE CC.contactid = ".intval($contactid)." 
					AND CC.current_company = 1
				LIMIT 1";
		
		$rs = $this->db->query($sql)->result();
		
		if (count($rs)) return $rs[0];
		else return false;
	}
}

?>